precision mediump float;

uniform sampler2D renderTexture;
uniform float u_offSet;
uniform float u_sigma;
uniform float u_blurringMode;

//0.0 = vertical / 1.0 = horizontal 
uniform float u_gaussDirection;


uniform int width;
uniform int height;

varying vec2 v_tc;

const float pi = 3.14159265;
vec4 computed_color;

void main(){

	if(u_blurringMode == 0.0){
	//do simple blur
		
		float x_offSet = u_offSet / float(width);
		float y_offSet = u_offSet / float(height);
		
		vec4 lowerLeftSample = texture2D(renderTexture, 
									vec2(v_tc.x - x_offSet,
										 v_tc.y - y_offSet));
										
		vec4 upperLeftSample = texture2D(renderTexture, 
									vec2(v_tc.x - x_offSet,
										 v_tc.y + y_offSet));
										
		vec4 upperRightSample = texture2D(renderTexture, 
									vec2(v_tc.x + x_offSet,
										 v_tc.y + y_offSet));
										 
		vec4 lowerRightSample = texture2D(renderTexture, 
									vec2(v_tc.x + x_offSet,
										 v_tc.y - y_offSet));
										 
		computed_color = (lowerLeftSample + upperLeftSample + upperRightSample + lowerRightSample) / 4.0;
	}
	
	else if(u_blurringMode == 1.0){
	//do Gaussian blur
	
		float pixelSize = 0.0;
		vec2 direction_vec = vec2(0.0, 0.0);
		
		if(u_gaussDirection == 0.0){
			pixelSize = 1.0 / float(width);
			direction_vec = vec2(0.0, 1.0);
			}
		else if(u_gaussDirection == 1.0){
			pixelSize = 1.0 / float(height);
			direction_vec = vec2(1.0, 0.0);
			}
		
		vec3 incrementalGaussian;
		incrementalGaussian.x = 1.0 / (sqrt(2.0 * pi) * u_sigma);
		incrementalGaussian.y = exp(-0.5 / (u_sigma * u_sigma));
		incrementalGaussian.z = incrementalGaussian.y * incrementalGaussian.y;
		
		vec4 colorSum = vec4(0.0, 0.0, 0.0, 0.0);
		float coefficientSum = 0.0;
		
		//Central Element
		colorSum += texture2D(renderTexture, v_tc) * incrementalGaussian.x;
		coefficientSum += incrementalGaussian.x;
		incrementalGaussian.xy *= incrementalGaussian.yz;
		
		//Neighbour Elements
		for(float i = 1.0; i <= u_offSet; i++){
			colorSum += texture2D(renderTexture, (v_tc - (i * pixelSize * direction_vec))) * incrementalGaussian.x;
			colorSum += texture2D(renderTexture, (v_tc + (i * pixelSize * direction_vec))) * incrementalGaussian.x;
			coefficientSum += (2.0 * incrementalGaussian.x);
			incrementalGaussian.xy *= incrementalGaussian.yz;
			}
			
		computed_color = colorSum / coefficientSum;
	
	}
	
	gl_FragColor = computed_color;
}